package com.TexasHoldem.ServerData.Quest;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import net.sf.json.JSONObject;

import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService;
import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService.QuestList.Builder;
import com.TexasHoldem.ServerData.PokerPlayer;
import com.TexasHoldem.db.TexasHoldemDB;

/**
 * @author su
 * 登录奖励
 */
public class PlayerLoginQuest implements PokerQuest
{
	public Long id;
	public NavigableMap<String,Integer> status = new TreeMap<String, Integer>(); 
	public static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
	public PokerPlayer pokerplayer;
	@Override
	public void OnQuestProcess()
	{
		if(pokerplayer.getStatistics().getLoginTime().get() == 0)
			return;
		// TODO Auto-generated method stub
		String curday = dateformat.format(new Date(pokerplayer.getStatistics().getLoginTime().get()));
		
		if(!status.containsKey(curday))
			status.put(curday, QUEST_FINISH);
		
		String preday = null;
		for(String date :status.keySet())
		{

			String day = date.split("-")[2];
			if(preday == null)
				preday = date.split("-")[2];
			if(Integer.parseInt(day) - Integer.parseInt(preday) == 1)
			{
				if(!status.containsKey(date))
					status.put(date, QUEST_FINISH);
				preday = day;
			}
			else if(Integer.parseInt(day) == 1 && Integer.parseInt(day) - Integer.parseInt(preday) < 0)
			{
				if(!status.containsKey(date))
					status.put(date, QUEST_FINISH);
				preday = day;
			}
			else if(Integer.parseInt(day) - Integer.parseInt(preday) > 1 || Integer.parseInt(day) - Integer.parseInt(preday) < 0)
			{
				status.clear();
				break;
			}

		}	

	}
	
	@Override
	public void OnInit(PokerPlayer pokerplayer)
	{
		// TODO Auto-generated method stub
		this.pokerplayer = pokerplayer;
		
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerLoginQuest.class.getSimpleName()).getQuestid();
		Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
		QueryRunner qr = new QueryRunner();

		String sql = "select id,player_id,questdata from playerquest where player_id=? and questId=?";
	    try {
	    	List results = (List) qr.query(c,sql,new BeanListHandler(QuestBean.class),pokerplayer.getId(),questid);
	    	
	    	for (int i = 0; i < results.size(); i++) {
	    		QuestBean gb = (QuestBean) results.get(i);
	    		this.id = gb.getId();
	    		this.status.putAll(JSONObject.fromObject(gb.getQuestdata()));
            }
	    	
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    finally
	    {
	    	DbUtils.closeQuietly(c);
	    }
	}

	@Override
	public void OnFinish(int questId,String questAwardParam)
	{
		QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerLoginQuest.class.getSimpleName());
		
		if(ql.getQuestid() != questId)
			return;
		
		
		if(status.containsKey(questAwardParam) && status.get(questAwardParam).equals(QUEST_FINISH))
		{
			int index = 1;
			for(String logindate:status.descendingKeySet())
			{
				if(logindate.equals(questAwardParam))
					break;
				index++;
			}
			QuestData qd = PokerQuestRule.getPokerQuestRule().getEvery_loginquest().get(index);
			
			pokerplayer.setYXB(pokerplayer.getYXB() + Integer.parseInt(qd.getAward()));
			status.put(questAwardParam, QUEST_AWARED);
		}
		
		
		
	}

	@Override
	public void OnSave()
	{
		// TODO Auto-generated method stub
		JSONObject js = new JSONObject();
		js.putAll(status);
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerLoginQuest.class.getSimpleName()).getQuestid();
		if(id != null)
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "update playerquest set player_id=?,questdata=?,questId=? where id=?";
		    try {
		        qr.update(c, sql, pokerplayer.getId(),js.toString(),questid,this.id);
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
		else
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "insert into playerquest (player_id, questdata,questId) values (?,?,?)";
		    try {
		    	qr.update(c, sql, pokerplayer.getId(),js.toString(),questid);
		        BigInteger newId = (BigInteger) qr.query(c, "select last_insert_id()", new ScalarHandler<BigInteger>(1));
		        this.id = newId.longValue();
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
		
		
	}

	@Override
	public void toQuest(Builder qb)
	{
		// TODO Auto-generated method stub
		
		TexasHoldemService.Quest.Builder quest = TexasHoldemService.Quest.newBuilder();
		int index = 1;
		for(String logindate:status.descendingKeySet())
		{
			QuestData qd = PokerQuestRule.getPokerQuestRule().getEvery_loginquest().get(index);
			QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerLoginQuest.class.getSimpleName());
			if(qd != null && status.containsKey(logindate) && status.get(logindate).equals(QUEST_FINISH))
			{
				quest.setAward(Integer.parseInt(qd.getAward()));
				quest.setCur(1);
				quest.setEnd(1);
				quest.setName(ql.getDesc());
				quest.setQuestId(ql.getQuestid());
				quest.setQuestAwardparam(logindate);
				qb.addQuests(quest);
				
			}

			index++;
		}
		
		
	}
	
}
